package com.base.hong.ui

import android.content.Intent
import android.os.*
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2
import com.base.hong.adapter.ViewPage2Adapter
import com.base.hong.databinding.ActivityMainBinding
import com.base.hong.ext.showToast
import com.htt.base_library.manager.ActivityManager
import com.base.hong.ui.base.BaseVMActivity
import com.base.hong.ui.main.HomeFragment
import com.base.hong.ui.main.ProjectFragment
import com.base.hong.ui.main.MineFragment


class MainActivity : BaseVMActivity<MainViewModel, ActivityMainBinding>() {


    var fragments = listOf<Fragment>(HomeFragment(), ProjectFragment(), MineFragment())

    override fun initView(intent: Intent?, savedInstanceState: Bundle?) {
        super.initView(intent, savedInstanceState)
        mViewBinding.tvHome.isSelected = true
        mViewBinding.tvExchange.isSelected = false
        mViewBinding.tvMine.isSelected = false
        val mAdapter = ViewPage2Adapter(fragments, this)
        mViewBinding.homeViewpage.adapter = mAdapter
        mViewBinding.homeViewpage.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                setSelected(position)
            }
        })
    }

    private fun setSelected(position: Int) {
        mViewBinding.tvHome.isSelected = position==0
        mViewBinding.tvExchange.isSelected = position==1
        mViewBinding.tvMine.isSelected = position==2
    }

    override fun setEventListener() {
lifecycleScope
        mViewBinding.tvHome.setOnClickListener {
            setSelected(0)
            mViewBinding.homeViewpage.currentItem = 0
        }
        mViewBinding.tvExchange.setOnClickListener {
            setSelected(1)
            mViewBinding.homeViewpage.currentItem = 1
        }
        mViewBinding.tvMine.setOnClickListener {
            setSelected(2)
            mViewBinding.homeViewpage.currentItem = 2
        }
        mViewBinding.homeViewpage.isUserInputEnabled = false
    }

    var exitTime: Long = 0
    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                //ToastUtils.showShort(R.string.exit_app)
                showToast("再按一次退出")
                exitTime = System.currentTimeMillis()
            } else {
                ActivityManager.exitApp()
            }
            return true
        }
        return super.dispatchKeyEvent(event)
    }


}